<script setup lang="ts">
import useStatusBarHeight from '@/composables/statusBarHeight'
import { isShowNavigationBarBackgroundKey } from '@/utils/keys'

interface NavigationBarProps {
  title: string
  titlePlacement?: 'center' | 'leading'
  frontColor?: string
  backgroundColor?: string
  isShowBackButton?: boolean
}

const props = withDefaults(defineProps<NavigationBarProps>(), {
  title: '',
  titlePlacement: 'center',
  frontColor: '#000000',
  backgroundColor: '#FFFFFF',
  isShowBackButton: true,
})

const router = useRouter()

// 由页面滚动决定是否显示导航栏背景，使用该自定义导航栏的页面有义务向下 provide 一个变量。
const isShowBackground = inject(
  isShowNavigationBarBackgroundKey,
  toRef(false),
)

// 当背景可见性发生变化时，同步改变状态栏的前景色
watch(isShowBackground, (newVal) => {
  if (newVal) {
    uni.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#FFFFFF',
    })
  }
  else {
    uni.setNavigationBarColor({
      frontColor: props.frontColor,
      backgroundColor: 'rgba(0, 0, 0, 0)',
    })
  }
}, { immediate: true })

// 动态获取状态栏高度
const statusBarHeight = useStatusBarHeight()

// 小程序胶囊按钮尺寸和定位信息
const menuButtonBoundingClientRect = uni.getMenuButtonBoundingClientRect()

// 导航栏部分的高度
const navigationBarHeight = computed(() => {
  // 导航栏高度 = 胶囊按钮高度 + 胶囊按钮与状态栏部分的间距 * 2
  return menuButtonBoundingClientRect.height + (menuButtonBoundingClientRect.top - statusBarHeight.value) * 2
})
</script>

<template>
  <!-- 容器 -->
  <view
    class="z-1000 fixed top-0 left-0 w-750rpx transition-all duration-300" :style="{
      color: props.frontColor,
      backgroundColor: isShowBackground ? props.backgroundColor : 'rgba(0, 0, 0, 0)',
    }"
  >
    <!-- 状态栏部分 -->
    <Spacer :height="statusBarHeight.toString()" unit="px" />
    <!-- 导航栏部分 -->
    <view
      class="relative w-full"
      :style="{ height: `${navigationBarHeight}px` }"
    >
      <!-- 返回按钮 -->
      <image
        v-if="isShowBackButton"
        class="absolute top-50% -transform-translate-y-50% left-15rpx w-48rpx h-48rpx"
        src="@/static/images/cheveron-left.png"
        @tap="router.back()"
      />
      <!-- 标题 -->
      <view
        class="absolute text-36rpx leading-36rpx font-bold"
        :style="{
          top: '50%',
          left: titlePlacement === 'center' ? '50%' : '30rpx',
          transform: titlePlacement === 'center' ? 'translateX(-50%) translateY(-50%)' : 'translateY(-50%)',
          color: isShowBackground ? '#000000' : props.frontColor,
        }"
      >
        {{ props.title }}
      </view>
    </view>
  </view>
</template>
